package com.traffic.between.service;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import com.traffic.between.config.BetweenProperties;


public class JieXunServiceImpl {
	private static Logger logger = Logger.getLogger(JieXunServiceImpl.class);
	public static JieXunServiceImpl service = new JieXunServiceImpl();
	
	private static String HOST_ORDER_PATH = BetweenProperties.JIEXUN_ORDER_URL;
	private static String JIEXUN_APPID = BetweenProperties.JIEXUN_APPID;
	private static String JIEXUN_SIGNATURE = BetweenProperties.JIEXUN_SIGNATURE;
	
	
    //servicecode, telecode, orderNo
	public String order(String servicecode, String telecode, String orderNo) {
		
        String result = "";
        
        Date date = new Date();
		DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
		String ts = format.format(date);
	
        List<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>();
        pairList.add(new BasicNameValuePair("appid",JIEXUN_APPID));
        pairList.add(new BasicNameValuePair("telecode",telecode));//充值手机号
        pairList.add(new BasicNameValuePair("timestamp",ts));//UNIX 时间戳
        pairList.add(new BasicNameValuePair("signtype","01"));
        pairList.add(new BasicNameValuePair("signature",JIEXUN_SIGNATURE));
        pairList.add(new BasicNameValuePair("servicecode",servicecode));
        pairList.add(new BasicNameValuePair("stream",orderNo));
       
		HttpPost httpPost = new HttpPost(HOST_ORDER_PATH);
		CloseableHttpClient client = HttpClients.createDefault();
		logger.info("between- 杰讯联合订购请求时的参数: " + pairList);
		try {
			httpPost.setEntity(new UrlEncodedFormEntity(pairList, "utf-8"));
			HttpResponse response = client.execute(httpPost);
			int statusCode = response.getStatusLine().getStatusCode();
			logger.info("between- 杰讯联合订购请求时的响应statusCode: " + statusCode);
			
			if (200 == statusCode) {
				HttpEntity entity = response.getEntity();
				result = EntityUtils.toString(entity, "utf-8");
				logger.info("between- 杰讯联合订购请求时的响应数据是: " + result);
			}
			
		} catch (Exception e) {
			logger.info("between- 杰讯联合订购请求时异常: " + e.getMessage());

		}
	
		return result;
	}

	
}
